package net.gazhi.delonix.rbac.service;

import java.sql.Timestamp;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

import net.gazhi.delonix.core.jpa.AbstractEntityService;
import net.gazhi.delonix.core.util.StringEncrypt;
import net.gazhi.delonix.rbac.entity.LoginUser;
import net.gazhi.delonix.rbac.entity.Role;
import net.gazhi.delonix.rbac.entity.User;
import net.gazhi.delonix.rbac.form.UserEditForm;
import net.gazhi.delonix.rbac.thread.RBACThreadContext;

@Service
public class UserService extends AbstractEntityService<User> {

	@Autowired
	private RoleService roleService;

	/**
	 * 加密密码，原文 sha256 之后，加盐再 sha256
	 * 
	 * @param passwd
	 * @return
	 */
	public String encryptPasswd(String passwd) {
		return encryptPostedPasswd(StringEncrypt.sha256(passwd));
	}

	/**
	 * 加密终端提交过来的密码，终端提交前，已对明文做了 sha256 处理<br>
	 * 只需加盐再 sha256 即可
	 * 
	 * @param postedPasswd
	 * @return
	 */
	public String encryptPostedPasswd(String postedPasswd) {
		return StringEncrypt.sha256(postedPasswd + "天生我才必有用").toUpperCase();
	}

	/**
	 * 根据账号查找用户
	 * 
	 * @param loginName
	 * @return
	 */
	public User findUser(String loginName) {
		return (User) super.createCriteria().add(Restrictions.eq("loginName", loginName)).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<User> list() {
		Criteria query = super.createCriteria().add(Restrictions.gt("id", LoginUser.SUPER_ADMIN_ID));
		query.addOrder(Order.asc("loginName"));
		return query.list();
	}

	@Transactional
	public void saveOrUpdate(UserEditForm form, BindingResult result) {
		if (form.getId() == LoginUser.SUPER_ADMIN_ID) {
			result.reject("UserEditForm.id.deniedsa", "不允许修改超级管理员！");
			return;
		}
		if (this.existedOther(form.getId(), "loginName", form.getLoginName())) {
			result.reject("UserEditForm.loginName", "登录账号重复！");
			return;
		}
		if (this.existedOther(form.getId(), "name", form.getName())) {
			result.reject("UserEditForm.name", "用户姓名重复！");
			return;
		}
		if (form.getId() == 0 && !StringUtils.hasLength(form.getLoginPasswd())) {
			result.reject("UserEditForm.loginPasswd", "密码不能为空！");
			return;
		}
		User user = form.getId() > 0 ? this.get(form.getId()) : new User();
		if (user == null) {
			result.reject("UserEditForm.id.notfound", "用户不存在（id=" + form.getId() + "）！");
			return;
		}
		BeanUtils.copyProperties(form, user, "loginName", "loginPasswd");
		if (StringUtils.hasLength(form.getLoginPasswd())) {
			user.setLoginPasswd(encryptPostedPasswd(form.getLoginPasswd()));
		}
		List<Role> roles = this.roleService.listAll();
		for (Role role : roles) {
			role.getId();
			// TODO: 设置角色
		}
		if (user.getId() == 0) {
			user.setLoginName(form.getLoginName());
			user.setCreateTime(new Timestamp(System.currentTimeMillis()));
			user.setCreatedBy(RBACThreadContext.getLoginUser().getLoginName());
		}
		user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		user.setUpdatedBy(RBACThreadContext.getLoginUser().getLoginName());
		dao.saveOrUpdate(user);
	}

}
